<?php namespace Phpcmf\Model\Order;

class Cart extends \Phpcmf\Model
{

    private $agent;
    private $cart_where;

    public function __construct(...$params)
    {
        parent::__construct(...$params);
        $this->agent = md5(\Config\Services::request(null, true)->getUserAgent().\Phpcmf\Service::L('Input')->ip_address());
        $this->cart_where = '((uid > 0 and uid='.(int)$this->uid.') or (agent="'.$this->agent.'" and uid=0))';
    }

    // 我的购物车商品数量
    public function my_count($mid) {

        $count = $this->db->table(SITE_ID.'_order_cart')
            ->selectSum('quantity')
            ->where('mid', $mid)
            ->where($this->cart_where)
            ->get()->getRowArray();

        return (int)$count['quantity'];
    }

    // 我的购物车商品详情
    public function my_list($mid) {

        $list = $this->db->table(SITE_ID.'_order_cart')->where('mid', $mid)->where($this->cart_where)->get()->getResultArray();
        if (!$list) {
            return [];
        }

        foreach ($list as $i => $t) {
            $rt = $this->get_module_row($mid, $t['cid'], $t['sku_value']);
            if (!$rt['code']) {
                unset($list[$i]);
                break;
            }
            // 价格获取
            $list[$i]['sn'] = $rt['data']['sn'];
            $list[$i]['price'] = $rt['data']['price'];
            //$list[$i]['quantity'] = $rt['data']['quantity'];
        }

        return $list;
    }

    // 我的购物车单个商品详情
    public function my_info($mid, $id) {

        $t = $this->db->table(SITE_ID.'_order_cart')->where('mid', $mid)->where('id', $id)->where($this->cart_where)->get()->getRowArray();
        if ($t) {
            $rt = $this->get_module_row($mid, $t['cid'], $t['sku_value']);
            if (!$rt['code']) {
                return [];
            }
            // 价格获取
            $t['price'] = $rt['data']['price'];
            $t['sn'] = $rt['data']['sn'];
            //$t['quantity'] = $rt['data']['quantity'];
            return $t;
        } else {
            return [];
        }
    }

    // 删除我的购物车商品
    public function my_delete($mid, $id) {

        $this->db->table(SITE_ID.'_order_cart')->where($this->cart_where)->where('id', $id)->delete();

        return $this->my_count($mid);
    }

    public function update_num($id, $num) {

        $this->db->table(SITE_ID.'_order_cart')->where('id', $id)->where($this->cart_where)->update([
            'quantity' => $num
        ]);
    }

    // 加入我的购物车
    public function add_cart($mid, $id, $sku, $num) {

        $rt = $this->get_module_row($mid, $id, $sku);
        if (!$rt['code']) {
            return $rt;
        }

        $data = $rt['data'];
        $cart = $this->db->table(SITE_ID.'_order_cart')->where('mid', $mid)->where($this->cart_where)->where('cid', $id)->where('sku_value', $sku)->get()->getRowArray();
        if ($cart) {
            // 更新
            $this->table(SITE_ID.'_order_cart')->update($cart['id'], [
                'url' => $data['url'],
                'price' => $data['price'],
                'title' => $data['title'],
                'thumb' => $data['thumb'],
                'quantity' => $cart['quantity']+$num,
            ]);
        } else {
            // 新增
            $this->table(SITE_ID.'_order_cart')->insert([
                'mid' => $mid,
                'uid' => (int)$this->uid,
                'agent' => $this->agent,
                'price' => $data['price'],
                'thumb' => $data['thumb'],
                'cid' => $data['id'],
                'title' => $data['title'],
                'url' => $data['url'],
                'sku_name' => dr_array2string($data['sku_name']),
                'sku_value' => $sku,
                'quantity' => $num,
                'inputtime' => SYS_TIME,
            ]);
        }

        return dr_return_data(1, 'ok');
    }

    public function my_items($mid, $ids) {
        return $this->db->table(SITE_ID.'_order_cart')->whereIn('id', $ids)->where('mid', $mid)->where($this->cart_where)->get()->getResultArray();
    }

    public function update_cart($id, $rt) {
        $this->table(SITE_ID.'_order_cart')->update($id, [
            'url' => $rt['url'],
            'price' => $rt['price'],
            'title' => $rt['title'],
            'thumb' => $rt['thumb'],
        ]);
    }

    public function get_module_row($mid, $id, $sku) {

        // 查询商品
        $data = $this->table(SITE_ID.'_'.$mid)->get($id);
        if (!$data) {
            return dr_return_data(0, dr_lang('此商品[%s]不存在', $id));
        } elseif (isset($data['zt']) && !$data['zt']) {
            return dr_return_data(0, dr_lang('此商品[%s]已经下架', $id));
        }

        // 价格获取
        $price_sku = dr_string2array($data['price_sku']);
        if ($price_sku) {
            if (!$sku) {
                return dr_return_data(0, dr_lang('此商品[%s]没有选择价格规格', $id));
            } elseif (!isset($price_sku['value'][$sku])) {
                return dr_return_data(0, dr_lang('此商品[%s]价格规格(%s)无效', $id, $sku));
            }
            $price = $price_sku['value'][$sku]['price'];
            $quantity = $price_sku['value'][$sku]['quantity'];
            $sn = $price_sku['value'][$sku]['sn'];
            list($sku_name, $sku_string) = dr_sku_name($sku, $price_sku, 1);
        } else {
            $price = $data['price'];
            $sn = $data['price_sn'];
            $quantity = $data['price_quantity'];
            $sku_name = '';
            $sku_string = '';
        }

        // 缩略图
        if (isset($data['thumb']) && $data['thumb']) {
            $thumb = (string)$data['thumb'];
            if (strpos($data['thumb'], '') === 0) {
                // 如果是多文件字段取第一个作为缩略图
                $image = dr_string2array($data['thumb']);
                if (isset($image['file'][0]) && $image['file'][0]) {
                    $thumb = (string)$image['file'][0];
                } elseif (isset($image[0]) && $image[0]) {
                    $thumb = (string)$image[0];
                }
            }
        } else {
            $thumb = '';
        }

        $data['sn'] = $sn;
        $data['thumb'] = $thumb;
        $data['price'] = $price;
        $data['quantity'] = $quantity;
        $data['sku_name'] = $sku_name;
        $data['sku_string'] = $sku_string;

        return dr_return_data(1, 'ok', $data);
    }
    
}